<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateUserRequest;
use App\Repositories\RoleRepository;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use App\Http\Requests\CreateUserRequest;
use Toastr, Auth, Image;

class UserController extends Controller
{
    protected $role, $user;
    protected $fields = [
        'username' => '',
        'realname' => '',
        'phone' => '',
        'sex' => '',
        'status' => 0,
    ];

    public function __construct(RoleRepository $role, UserRepository $user)
    {
        parent::__construct();
        $this->role = $role;
        $this->user = $user;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = $this->user->paginate();
        return view('user.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['roles'] = $this->role->all();
        return view('user.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \App\Http\Requests\CreateUserRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(CreateUserRequest $request)
    {
        $data = $request->all();
        $data['avatar'] = asset('/assets/img/avatar.png');
        if ($user = $this->user->create($data)) {
            $user->attachRole($data['role']);
            Toastr::success('添加成功');
            return redirect('/user');
        }
        Toastr::error('添加失败');
        return redirect('/user');
    }

    public function profile()
    {
        $user = Auth::user();
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $user->$field);
        }
        $data['roles'] = $this->role->all();
        return view('user.profile', $data);
    }

    public function changeAvatar(Request $request)
    {
        $file = $request->file('avatar');
        $input = ['image' => $file];
        $rules = ['image' => 'image'];
        $validator = \Validator::make($input, $rules);
        if ($validator->fails()) {
            \Response::json([
                'status' => 'faild',
                'message' => $validator->getMessageBag()->toArray()
            ]);
        }
        $avatarPath = 'uploads/avatars/';
        $fileName = Auth::user()->id . '-'. time() . $file->getClientOriginalName();
        $file->move($avatarPath, $fileName);
        Image::make($avatarPath.$fileName)->fit(500)->save();

        return \Response::json([
            'status' => 'success',
            'avatar' => asset($avatarPath . $fileName),
            'image' => $avatarPath . $fileName
        ]);

    }

    public function cropAvatar(Request $request)
    {
        $data = $request->all();
        $photo = $data['photo'];
        $x = (int) $data['x'];
        $y = (int) $data['y'];
        $w = (int) $data['w'];
        $h = (int) $data['h'];
        $user['avatar'] = asset($photo);
        Image::make($photo)->crop($w, $h, $x, $y)->save();
        $this->user->update($user, Auth::user()->id);

        return redirect('user/index');

    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = $this->user->find($id);
        $data['id'] = $id;
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $user->$field);
        }
        $data['roles'] = $this->role->all();
        return view('user.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \App\Http\Requests\UpdateUserRequest $request
     * @param int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUserRequest $request, $id)
    {
        dd($request->all());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if ($this->user->delete($id)) {
            Toastr::success('删除成功');
            return redirect('/user');
        } else {
            Toastr::error('删除失败');
            return redirect('/user');
        }
    }
}
